from machine import Pin
from machine import I2S
import audio
from utils import file,common

# ======= I2S CONFIGURATION =======
SCK_PIN = 2
WS_PIN = 15
SD_PIN = 13
I2S_ID = 0
BUFFER_LENGTH_IN_BYTES = 40000
# ======= I2S CONFIGURATION =======

audio_in = I2S(
    I2S_ID,
    sck=Pin(SCK_PIN),
    ws=Pin(WS_PIN),
    sd=Pin(SD_PIN),
    mode=I2S.RX,
    bits=audio.WAV_SAMPLE_SIZE_IN_BITS,
    format=audio.FORMAT,
    rate=audio.SAMPLE_RATE_IN_HZ,
    ibuf=BUFFER_LENGTH_IN_BYTES,
)

def record_buffer():
    mic_samples = bytearray(10000)
    num_sample_bytes_read = 0

    total_mic_read_buffer = bytearray(audio.wav_header) #完整音频数据

    print("Recording size: {} bytes".format(audio.RECORDING_SIZE_IN_BYTES))
    print("==========  START RECORDING ==========")
    while num_sample_bytes_read < audio.RECORDING_SIZE_IN_BYTES:
        common.collect_gc(True)
        num_bytes_read_from_mic = audio_in.readinto(mic_samples)
        total_mic_read_buffer += mic_samples[:num_bytes_read_from_mic]
        num_sample_bytes_read += num_bytes_read_from_mic
    print("==========  DONE RECORDING ==========")
    audio_in.deinit()
    return memoryview(total_mic_read_buffer)

def record_to_file():
    mic_samples = bytearray(10000)
    mic_samples_mv = memoryview(mic_samples)
    num_sample_bytes_written_to_wav = 0
    wav_file = audio.create_wav_file()

    print("Recording size: {} bytes".format(audio.RECORDING_SIZE_IN_BYTES))
    print("==========  START RECORDING ==========")
    while num_sample_bytes_written_to_wav < audio.RECORDING_SIZE_IN_BYTES:
        # read a block of samples from the I2S microphone
        num_bytes_read_from_mic = audio_in.readinto(mic_samples_mv)
        if num_bytes_read_from_mic > 0:
            num_bytes_to_write = min(
                num_bytes_read_from_mic, audio.RECORDING_SIZE_IN_BYTES - num_sample_bytes_written_to_wav
            )
            # write samples to WAV file
            num_bytes_written = wav_file.write(mic_samples_mv[:num_bytes_to_write])
            num_sample_bytes_written_to_wav += num_bytes_written

    print("==========  DONE RECORDING ==========")

    # cleanup
    wav_file.close()
    audio_in.deinit()
    print(f"file: {audio.WAV_FILE}, size: {file.get_file_size(audio.WAV_FILE) // 1024}KB")

